package org.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.service.CakeCatelogService;
import org.example.bean.CakeCatalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.example.utils.Result;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
public class CakeCatalogController {

    private CakeCatelogService cakecatalogService;

    @Autowired
    public void setCatalogService(CakeCatelogService cakecatelogService) {
        this.cakecatalogService = cakecatelogService;
    }

    @ResponseBody
    @RequestMapping("/selectAll")
    public Result catalogListServlet() {
        List<CakeCatalog> catalogs = cakecatalogService.selectAll();
        System.out.println("查询所有分类方法执行成功");
        Result result = new Result();
        result.result = catalogs;
        return result;
    }
    @ResponseBody
    @PostMapping("/deleteId")
    public Result delServlet(String id){
        cakecatalogService.deleteId(Integer.parseInt(id));
        System.out.println("删除操作执行成功");
        Result res = new Result();
        res.flag = 1;
        return res;
    }

    @ResponseBody
    @PostMapping("/addCakeCatalog")
    public Result addCakeCatalogServlet(String param) {
        JSONArray json = JSON.parseArray(param);
         System.out.println(json);
        List<CakeCatalog> list = new ArrayList<>();
        Iterator<Object> it = json.iterator();
        System.out.println(it);
        while(it.hasNext()) {
            JSONObject next = (JSONObject)it.next();
            System.out.println(next);
            CakeCatalog cata = new CakeCatalog();
            cata.setTitle(next.getString("title"));
            cata.setInfo(next.getString("info"));
            String title = next.getString("type");
            System.out.println("所选择的type代入为以title参数的查询方法");
            CakeCatalog father = cakecatalogService.selectByTitle(title);
            System.out.println("获取到以的信息视为父类信息");
            cata.setLevelId(father.getLevelId() + 1);
            System.out.println("输入的信息则是父类信息下的子类信息levelId则应该+1");
            cata.setParentId(father.getId());
            System.out.println("parentId则就是父类的id");
            list.add(cata);
            System.out.println(list);
        }
        System.out.println("即将执行添加操作");
        cakecatalogService.insert(list);
        System.out.println("添加操作执行成功");
        Result res = new Result();
        res.flag = 1;
        res.result = "/view/catalog_list";
        return res;
    }



}
